#include "joystick.hpp"
#include <fcntl.h>
#include <linux/joystick.h>
#include <unistd.h>

enum JSEventType : unsigned char
{
    Button = 0x01,
    Axis = 0x02,
    Init = 0x80
};

bool JoyStick::InitDevice(std::string dev)
{
    fd = open(dev.c_str(), O_RDWR | O_NONBLOCK);
    if (fd < 0)
        return false;
    return true;
}

float JoyStick::GetAix(int number)
{
    auto result = state.aixsValue.find(number);
    if (result != state.aixsValue.end())
        return result->second;
    else
        // std::cerr << "Invalid Aix number out of range." << std::endl;
        return 0.0f;
}

bool JoyStick::GetButton(int number)
{
    auto result = state.buttonValue.find(number);
    if (result != state.buttonValue.end())
        return result->second;
    else
        // std::cerr << "Invalid Button number out of range." << std::endl;
        return false;
}

void JoyStick::CheckDeviceInput()
{
    js_event jsevent;
    while (true)
    {
        int number = read(fd, &jsevent, sizeof(jsevent));
        if (number < 0)
        {
            break;
        }
        jsevent.type &= ~JSEventType::Init;
        if (jsevent.type == JSEventType::Axis)
        {
            state.aixsValue[jsevent.number] = jsevent.value / 32767.0f;
        }
        else if (jsevent.type == JSEventType::Button)
        {
            state.buttonValue[jsevent.number] = jsevent.value == 1;
        }
    }
}

JoyStick::~JoyStick()
{
    close(fd);
}
